<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的消息 - 校园二手交易</title>
    <link rel="stylesheet" href="css/style.css"> <!-- 假设有一个全局样式文件 -->
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f6f8;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: flex-start; /* Align to top */
            min-height: 100vh; 
        }
        .container {
            width: 100%;
            max-width: 800px;
            margin-top: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .header {
            background-color: #4a89dc;
            color: white;
            padding: 20px;
            text-align: center;
            font-size: 24px;
        }
        .message-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .message-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .message-item:hover {
            background-color: #f9f9f9;
        }
        .message-item:last-child {
            border-bottom: none;
        }
        .avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #ddd;
            margin-right: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #fff;
        }
        .message-details {
            flex-grow: 1;
        }
        .user-name {
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 5px;
        }
        .last-message {
            font-size: 14px;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 400px; /* Adjust as needed */
        }
        .message-meta {
            text-align: right;
            min-width: 80px; /* Ensure space for time and badge */
        }
        .timestamp {
            font-size: 12px;
            color: #999;
            margin-bottom: 5px;
        }
        .unread-badge {
            background-color: #e74c3c;
            color: white;
            font-size: 12px;
            padding: 3px 8px;
            border-radius: 12px;
            font-weight: bold;
        }
        .no-messages {
            text-align: center;
            padding: 50px;
            color: #888;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            我的消息
        </div>
        <ul class="message-list" id="messageList">
            <!-- 消息列表项将通过JavaScript动态插入 -->
            <!-- 示例结构:
            <li class="message-item" data-user-id="1">
                <div class="avatar">U1</div>
                <div class="message-details">
                    <div class="user-name">用户1</div>
                    <div class="last-message">这是最后一条消息的预览...</div>
                </div>
                <div class="message-meta">
                    <div class="timestamp">10:30 AM</div>
                    <span class="unread-badge">3</span>
                </div>
            </li>
            -->
        </ul>
        <div id="noMessages" class="no-messages" style="display: none;">
            暂无消息
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 登录状态判断已注释掉 -- 根据用户要求
            /*
            const currentUserString = localStorage.getItem('currentUser');
            if (!currentUserString) {
                alert('请先登录！ (原因: 未找到登录信息)');
                window.location.href = 'login.html'; // Redirect to login page
                return;
            }

            let currentUser;
            try {
                currentUser = JSON.parse(currentUserString);
            } catch (e) {
                console.error('解析localStorage中的currentUser失败:', e, '存储的值为:', currentUserString);
                alert('登录信息格式错误，请尝试重新登录。');
                localStorage.removeItem('currentUser');
                localStorage.removeItem('token');
                window.location.href = 'login.html';
                return;
            }

            if (!currentUser || (!currentUser.userId && !currentUser.id)) {
                console.error('currentUser对象存在，但userId和id都缺失或无效:', currentUser);
                alert('请先登录！ (原因: 登录信息不完整，缺少用户标识)');
                window.location.href = 'login.html'; // Redirect to login page
                return;
            }

            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录！ (原因: 会话令牌丢失)');
                window.location.href = 'login.html';
                return;
            }
            */

            // 尝试获取currentUser以供fetchMessageContacts使用
            // 注意：如果用户未登录，currentUser可能为null，导致后续操作失败
            let currentUserForApi;
            try {
                const storedUser = localStorage.getItem('currentUser');
                if (storedUser) {
                    currentUserForApi = JSON.parse(storedUser);
                }
            } catch (e) {
                console.error('获取或解析currentUser失败（登录检查已移除）:', e);
                // 可以在这里决定是否显示错误或重定向，但目前按用户要求不主动检查登录
            }

            if (currentUserForApi && (currentUserForApi.userId || currentUserForApi.id)) {
                fetchMessageContacts(currentUserForApi.userId || currentUserForApi.id);
            } else {
                // 如果没有有效的currentUser信息，可以显示提示或不加载列表
                console.warn('无法获取有效的用户信息来加载消息列表（登录检查已移除）。');
                const noMessagesDiv = document.getElementById('noMessages');
                if (noMessagesDiv) {
                    noMessagesDiv.textContent = '无法加载消息列表，请确保您已登录。';
                    noMessagesDiv.style.display = 'block';
                }
                const messageList = document.getElementById('messageList');
                if(messageList) messageList.innerHTML = ''; // 清空列表
            }
        });

        function fetchMessageContacts(userId) {
            // TODO: 替换为真实的API端点
            // 这个API应该返回一个包含对话列表的数组
            // 每个对话对象应包含: otherUserId, otherUserName, lastMessage, timestamp, unreadCount
            const apiUrl = `/api/messages/conversations?userId=${userId}`;

            fetch(apiUrl, {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token') // 如果需要认证
                }
            })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401) {
                        alert('会话已过期，请重新登录。');
                        localStorage.removeItem('currentUser');
                        localStorage.removeItem('token');
                        window.location.href = 'login.html';
                        throw new Error('Unauthorized');
                    }
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(conversations => {
                renderMessageList(conversations);
            })
            .catch(error => {
                console.error('获取消息列表失败:', error);
                const messageList = document.getElementById('messageList');
                const noMessagesDiv = document.getElementById('noMessages');
                messageList.innerHTML = ''; // 清空任何可能的旧内容
                noMessagesDiv.textContent = '加载消息列表失败，请稍后再试。';
                noMessagesDiv.style.display = 'block';
            });
        }

        function renderMessageList(conversations) {
            const messageList = document.getElementById('messageList');
            const noMessagesDiv = document.getElementById('noMessages');
            messageList.innerHTML = ''; // 清空现有列表

            if (!conversations || conversations.length === 0) {
                noMessagesDiv.textContent = '暂无消息';
                noMessagesDiv.style.display = 'block';
                return;
            }
            noMessagesDiv.style.display = 'none';

            conversations.forEach(convo => {
                const listItem = document.createElement('li');
                listItem.classList.add('message-item');
                listItem.setAttribute('data-user-id', convo.otherUserId);
                listItem.setAttribute('data-user-name', convo.otherUserName); // Store username for chat page

                // 生成简单的字符头像
                const avatarText = convo.otherUserName ? convo.otherUserName.substring(0, 2).toUpperCase() : '??';

                listItem.innerHTML = `
                    <div class="avatar" style="background-color: ${getRandomColor(convo.otherUserId)};">${avatarText}</div>
                    <div class="message-details">
                        <div class="user-name">${convo.otherUserName || '未知用户'}</div>
                        <div class="last-message">${convo.lastMessage || '...'}</div>
                    </div>
                    <div class="message-meta">
                        <div class="timestamp">${formatTimestamp(convo.timestamp)}</div>
                        ${convo.unreadCount > 0 ? `<span class="unread-badge">${convo.unreadCount}</span>` : ''}
                    </div>
                `;

                listItem.addEventListener('click', function() {
                    // 直接消息功能已移除，因为我们正在将交流功能集成到商品详情页的评论区。
                    // 如果未来需要直接消息，请重新设计此处的逻辑。
                    alert('直接消息功能已移除，请在商品详情页参与评论。');
                    // const otherUserId = this.getAttribute('data-user-id');
                    // const otherUserName = this.getAttribute('data-user-name');
                    // // 跳转到聊天页面，并传递对方用户ID和用户名
                    // window.location.href = `chat.html?userId=${otherUserId}&userName=${encodeURIComponent(otherUserName)}`;
                });
                messageList.appendChild(listItem);
            });
        }

        function formatTimestamp(isoTimestamp) {
            if (!isoTimestamp) return '';
            const date = new Date(isoTimestamp);
            // 简单的日期格式化，可以根据需要做得更复杂
            const today = new Date(); 
            if (date.toDateString() === today.toDateString()) {
                return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            }
            return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        }

        // Function to generate a consistent random color based on user ID for avatar
        function getRandomColor(userId) {
            let hash = 0;
            const strUserId = String(userId);
            for (let i = 0; i < strUserId.length; i++) {
                hash = strUserId.charCodeAt(i) + ((hash << 5) - hash);
            }
            const c = (hash & 0x00FFFFFF).toString(16).toUpperCase();
            return "#" + "00000".substring(0, 6 - c.length) + c;
        }

    </script>
</body>
</html>
